package com.linjiahao.nettyOne.handler.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.linjiahao.nettyOne.constant.HandlerServiceName;
import com.linjiahao.nettyOne.handler.AbstractHandle;
import com.linjiahao.nettyOne.handler.HandlerServiceFactory;
import com.linjiahao.nettyOne.server.SendMessage;
import com.linjiahao.nettyOne.service.ChatListService;
import com.linjiahao.nettyOne.vo.ChatListVO;
import com.linjiahao.servicebase.common.ResultMap;
import com.linjiahao.servicebase.vo.NettyMessageVO;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @ClassName ChatListHandler
 * @Description: 获取实时聊天列表和搜索
 * @Author linjiahao
 * @Date 10/1/2022
 **/
@Service
@Slf4j
public class ChatListHandler implements AbstractHandle, InitializingBean {


    @Autowired
    private ChatListService chatListService;

    @Override
    public String getServiceTypeName() {
        return HandlerServiceName.CURRENT_FRIEND_CHAT_LIST.getName();
    }

    @Override
    public Object handlerWebsocket(ChannelHandlerContext ctx, Object message) {
        NettyMessageVO nettyMessageVO = (NettyMessageVO)message;
        List<ChatListVO> list = chatListService.getCurrentChatList(nettyMessageVO.getUserId(),
                nettyMessageVO.getPageNo(),nettyMessageVO.getPageSize());
        nettyMessageVO.setData(JSON.toJSONString(list));
        ctx.channel().writeAndFlush(new TextWebSocketFrame(JSON.toJSONString(nettyMessageVO)));
        log.info("用户{}的聊天列表获取成功",nettyMessageVO.getUserId());
        return null;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        HandlerServiceFactory.register(getServiceTypeName(),this);
    }
}
